package com.qf.springbootshiro.shiroconfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.springbootshiro.user.entity.User;
import com.qf.springbootshiro.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        List<String> roles = getRoleFromDb(user);
        List<String> Permissions = getPermissionFromDb(user);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(Permissions);
        return simpleAuthorizationInfo;
    }

    private List<String> getPermissionFromDb(User user) {
        return userService.getPermission(user);
    }

    private List<String> getRoleFromDb(User user) {
        return userService.getRole(user);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户名
        final String username = (String) token.getPrincipal();

        // 根据用户名查询数据库，得到user对象
        User user = getUserFromDB(username);

        if (user == null) {
            throw new UnknownAccountException();
        }

        final SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());

        return authenticationInfo;
    }

    private User getUserFromDB(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        return userService.getOne(userQueryWrapper);
    }
}
